<?php

namespace App\Models;

use App\Http\Helper\PingppHelper;
use App\Http\Controllers\Weixin\WechatTemplateController;
use App\Http\Helper\UrlSchemaHelper;
use App\Http\Helper\YunXinServerAPI;
use App\Models\ContributionValueLog;
use App\Models\SocialStatusLog;

/**
 * Class Purchase
 * @property integer id ID
 * @property integer user_id 用户ID
 * @property integer seller_user_id 卖家ID
 * @property integer product_id 商品ID
 * @property float total 订单金额
 * @property integer is_payed 是否支付
 * @property string pay_method 支付方式
 * @property integer status 订单状态
 * @property integer return_status 退款状态
 * @property integer count 数量
 * @property integer sort 排序
 * @property string server_date 服务时间
 * @property string order_no 订单编号
 * @property string source 订单来源
 * @property string type 订单类型model_name
 * @property string cancel_name 取消订单操作员姓名
 * @property string cancel_note 取消订单原因
 * @property date pay_date 支付时间
 * @property date close_date 关闭时间
 * @property date accept_date 接单时间
 * @property integer coupon_number_id 用户优惠券id
 * @property date accept_end_date 接单结束时间
 * @property Product product 商品信息
 * @property User user 用户信息
 * @property User seller_user 卖家用户信息
 * @property Dynamic dynamic 动态
 * @property Vip vip 会员
 * @property CouponNumber couponNumber 优惠券
 */
class Purchase extends ApplicationModel
{
    protected $fillable = [
        'user_id',
        'product_id',
        'total',
        'is_payed',
        'pay_method',
        'status',
        'order_no',
        'source',
        'pay_date',
        'close_date',
        'accept_date',
        'seller_user_id',
        'return_status',
        'count',
        'server_date',
        'unread',
        'sort',
        'type',
        'cancel_name',
        'cancel_note',
        'accept_end_date',
        'coupon_number_id',
        'coupon_total',
        'product_total',
        'remark',
        'times',
        'refund_created_at',
        'cancel_times',
        'coin',
        'gift_coin',
        'question_id',
        'question',
        'theme_id',
        'theme',
        'tipping_type',
        'anonymous',
        'answer_date',
        'device_type',
        'device_token',
        'os_version',
        'app_version',
        'to_user_id',
        'video_id',
        'video_url',
        'user_delete_flag',
        'seller_delete_flag',
        'answer_time',
        'prepay_id'
    ];
    const PAY_WAITING = false;//待支付
    const PAY_SUCCESS = true;//已支付

    const STATUS_WAITING = 1;//等待付款
    const STATUS_BUYER_CANCEL = 2;//买家取消订单
    const STATUS_OVERTIME_PAYMENT = 3;//超时未付款
    const STATUS_SELLER_CANCEL = 4;//卖家取消订单（拒单）
    const STATUS_SELLER_ACCEPT_WAITING = 5;//等待卖家接单
    const STATUS_SELLER_ACCEPT = 6;//卖家接单
    const STATUS_SELLER_OVERTIME = 7;//卖家超时未接单
    const STATUS_FINISH = 8;//订单完成
    const STATUS_ADMIN_CANCEL = 9;//后台强制取消

    const STATUS_REFUND_AUDIT = 11;  //退款申请审核中
    const STATUS_REFUND_REJECT = 13;  //退款申请拒绝
    const STATUS_REFUND_PASS = 12;  //退款申请通过
    const STATUS_REFUND_WITHDRAW = 14;  //退款申请撤销


    const STATUS_SELLER_CANCEL_AUDIT = 16;  //卖家取消订单 等待买家通过
    const STATUS_SELLER_CANCEL_PASS = 17;  //卖家取消订单 买家通过



    const STATUS_REFUND_ACCEPT_OVERTIME = 15;  //退款申请超时 卖家自动通过
    const STATUS_SELLER_CANCEL_OVERTIME = 18;  //卖家取消订单申请 超时通过 买家通过


    const RETURN_STATUS_WAITING = 1;//退款中
    const RETURN_STATUS_SUCCESS = 2;//退款成功

    const SOURCE_CHUGE = 'chuge_activity';
    const SOURCE_APP = 'app';

    public function pay_status_desc()
    {
        switch ($this->status) {
            case static::STATUS_WAITING:
                return "等待付款";
                break;
            case static::STATUS_SELLER_ACCEPT_WAITING:
                return "等待卖家接单";
                break;
            case static::STATUS_SELLER_CANCEL:
                return "卖家取消订单";
                break;

            default;
        }
    }

    public function return_status_desc()
    {
        if ($this->return_status == static::RETURN_STATUS_WAITING) {
            return "退款中";
        }
        if ($this->return_status == static::RETURN_STATUS_SUCCESS) {
            return "退款成功";
        }
    }

    static function boot()
    {
        parent::boot();
        static::creating(function (Purchase $purchase) {
            $purchase->before_create();
            $purchase->is_payed = Purchase::PAY_WAITING;
            $purchase->status = Purchase::STATUS_WAITING;
            $purchase->sort = 1;
            $purchase->order_no = date('YmdHis') . rand(10000, 99999);


        });
        static::created(function (Purchase $purchase) {
            if ($purchase->total == 0) {
                $purchase->total = $purchase->total($purchase->user_id);
                $coupon_number_id =  intval($purchase->coupon_number_id);
                $total =  intval( $purchase->total );
                if( $coupon_number_id > 0 && $total == 0 )
                {
                          $purchase->product_total = $purchase->product_total($purchase->user_id);
                          $purchase->coupon_total =  $purchase->couponNumber->coupon_real_price();
                          $purchase->is_payed = Purchase::PAY_SUCCESS;
                          $purchase->pay_method = 'coupon';
                          $purchase->status = Purchase::STATUS_SELLER_ACCEPT_WAITING;
                          $purchase->sort = 2;
                          $purchase->pay_date = date('Y-m-d H:i:s');
                }

                if( $coupon_number_id == 0 && $total == 0 )
                {
                    $purchase->product_total = $purchase->product_total($purchase->user_id);
                    $purchase->coupon_total = 0;
                    $purchase->is_payed = Purchase::PAY_SUCCESS;
                    $purchase->pay_method = 'free';
                    $purchase->status = Purchase::STATUS_SELLER_ACCEPT_WAITING;
                    $purchase->sort = 2;
                    $purchase->pay_date = date('Y-m-d H:i:s');
                }


                if($coupon_number_id>0)
                {

                    $purchase->coupon_total =  $purchase->couponNumber->coupon_real_price();
                    $purchase->product_total = $purchase->product_total($purchase->user_id) + $purchase->coupon_total;
                }

                if( $coupon_number_id==0 )
                {
                    $purchase->product_total = $purchase->product_total($purchase->user_id);
                }

                $purchase->save();
            }
        });
    }

    public function scopeChuge($query)
    {
        return $query->where('source', static::SOURCE_CHUGE);
    }

    public function scopeProductType($query)
    {
        return $query->where('type', 'Product')->where('source', '!=', 'import');
    }

    public function scopeServing($query)
    {
        return $query->whereIn('status', [Purchase::STATUS_WAITING, Purchase::STATUS_SELLER_ACCEPT_WAITING, Purchase::STATUS_SELLER_ACCEPT, Purchase::STATUS_FINISH]);
    }

    public function scopeDynamicType($query)
    {
        return $query->where('type', 'Dynamic');
    }
    public function scopeFinish($query){
        return $query->where('status',8);
    }
    public function scopeNotFinish($query){
        return $query->whereIn('status',[static::STATUS_WAITING,static::STATUS_SELLER_ACCEPT_WAITING,static::STATUS_SELLER_ACCEPT]);
    }

    public function before_create()
    {
        $this->_is_my_product();
        $this->check_coupon();
    }

    public function check_coupon()
    {
        if ($this->coupon_number_id)
        {
            $coupon_number = $this->couponNumber;
            if (!$coupon_number) {
                throw new \Exception('优惠券不存在');
            }
            if($coupon_number->user_id != $this->user_id)
            {
                return responseMsg(false, '非法请求');
            }
            $flag =  $coupon_number->valid_coupon($this->product_id, $this->count,$this->user_id);
            if ( !$flag && $flag===false) {
                throw new \Exception('此优惠券不可用');
            }
            $coupon_number->status = false;
            $coupon_number->save();
        }
    }

    public function refund_coupon()
    {
        if ($this->coupon_number_id) {
            $coupon_number = $this->couponNumber;
            $coupon_number->status = true;
            $coupon_number->save();
        }
    }

    public function question_payed()
    {
        $this->question_payed_sms();
        $this->app_question_payed_push();
        $this->send_question_payed_msg();

    }

    public function answer_finish_msg()
    {
        $this->app_answer_finish_push();
        $this->send_answer_finish_msg();

    }


    public function payed()
    {
        $this->get_accept_end_time();
        $this->payed_sms();
        $this->app_payed_push();
    }

    /**
     * 根据服务时间获取接单超时时间
     */
    public function get_accept_end_time(){
        //计算接单结束时间
        if(date("Y-m-d H:i:s",strtotime($this->server_date)) < date("Y-m-d H:i:s",strtotime('+12 hour'))){
            $this->accept_end_date = date('Y-m-d H:i:s',strtotime('+1 hour', strtotime($this->created_at)));
            $this->save();
        }else if(date("Y-m-d H:i:s",strtotime($this->server_date)) < date("Y-m-d H:i:s",strtotime('+24 hour'))){
            $this->accept_end_date = date('Y-m-d H:i:s',strtotime('+4 hour', strtotime($this->created_at)));
            $this->save();
        }else{
            $this->accept_end_date = date('Y-m-d H:i:s',strtotime('+12 hour', strtotime($this->created_at)));
            $this->save();
        }
    }


    public function app_answer_finish_push()
    {
        if ($this->type == 'Question')
        {
            $content = sprintf(Message::ANSWER, $this->answer_user->name);
            $this->save_answer_msg($content, $this->user_id, "{'url':'" . UrlSchemaHelper::get_url_schema("answer") . $this->id . "'}");
        }
    }
    /**
     * 订单支付成功，给卖家推送消息
     */
    public function app_question_payed_push()
    {
        if ($this->type == 'Question')
        {
            $name =  $this->user->name;
            $anonymous = $this->anonymous;
            if( $anonymous == 1 )
            {
                $name = '神秘人';
            }
            $content = sprintf(Message::QUESTION_PAYED, $name);

            \Log::info($content, ['======app_question_payed_push====content===']);

            $this->save_question_msg($content, $this->to_user_id, "{'url':'" . UrlSchemaHelper::get_url_schema("question") . $this->id . "'}");
        }
    }



    public function send_answer_finish_msg()
    {

        $url = UrlSchemaHelper::get_url_schema('myanswervideo');
        $content = sprintf(Message::ANSWER, $this->answer_user->name);
        $message = new Message();
        $message->user_id = $this->user_id;
        $message->content = $content;
        $message->icon = Message::ICON;
        $message->url_schema = $url;
        $message->type_id = $this->id;
        $message->save();
        //$message->pushMsg($this->user_id, $content,"{'url':'" . $url . "'}");
    }

    public function send_question_payed_msg()
    {

        $url = UrlSchemaHelper::get_url_schema('myvideo');
        $name =  $this->user->name;
        $anonymous = $this->anonymous;
        if( $anonymous == 1)
        {
            $name = '神秘人';
        }
        $content = sprintf(Message::QUESTION_PAYED, $name);

        \Log::info($content, ['======send_question_payed_msg====content===']);

        $message = new Message();
        $message->user_id = $this->to_user_id;
        $message->content = $content;
        $message->icon = Message::ICON;
        $message->url_schema = $url;
        $message->type_id = $this->id;
        $message->save();
       // $message->pushMsg($this->to_user_id, $content,"{'url':'" . $url . "'}");
    }

    /**
     * 订单支付成功，给卖家推送消息
     */
    public function app_payed_push()
    {
        if ($this->type == 'Product') {
            $this->save_msg(Message::PURCHASE_PAYED, $this->seller_user_id, "{'url':'" . UrlSchemaHelper::get_url_schema("seller_order") . $this->id . "'}");
            $this->check_night_time();
        }
    }

    /**
     * 验证是否为危险时间
     * 订单服务时间在晚间21点至凌晨7点之间，卖家接单后，对买家进行安全提示
     */
    public function check_night_time()
    {
        $checkDayStr = date('Y-m-d H:i:s', strtotime($this->server_date));
        $startTime = date('Y-m-d', strtotime($this->server_date)) . ' 21:00:00';
        $endTime = date('Y-m-d', strtotime('+1 day', strtotime($this->server_date))) . ' 07:00:00';
        if ($checkDayStr > $startTime && $checkDayStr < $endTime) {
            $this->send_night_msg();
        }
        $startTime = date('Y-m-d', strtotime('-1 day', strtotime($this->server_date))) . ' 21:00:00';
        $endTime = date('Y-m-d', strtotime($this->server_date)) . ' 07:00:00';
        if ($checkDayStr > $startTime && $checkDayStr < $endTime) {
            $this->send_night_msg();
        }
    }

    /**
     * 发送夜间提示短信
     */
    public function send_night_msg()
    {
        //发送推送
        $message = new Message();
        $message->pushMsg($this->seller_user_id, '重要：夜间服务请注意人身安全，如遇紧急情况请立即拨打110');
        $yunXinServerAPI = new YunXinServerAPI();
        $yunXinServerAPI->payedNightTemplate($this->seller_user->phone());
    }

    /**
     * 卖家拒单，给买家推送消息
     */
    public function app_reject_push()
    {
        $content = sprintf(Message::PURCHASE_REJECT, $this->seller_user->name);
        $this->save_msg($content, $this->user_id, "{'url':'" . UrlSchemaHelper::get_url_schema("order") . $this->id . "'}");
    }




    /**
     * 后台强制取消订单，给卖家、买家推送消息
     */
    public function app_admin_cancel_push()
    {
        $content = sprintf(Message::ADMIN_CANCEL_BUYER, $this->seller_user->name, $this->order_no);
        $this->save_msg($content, $this->user_id, "{'url':'" . UrlSchemaHelper::get_url_schema("order") . $this->id . "'}");
        $content = sprintf(Message::ADMIN_CANCEL_SELLER, $this->user->name, $this->order_no);
        $this->save_msg($content, $this->seller_user_id, "{'url':'" . UrlSchemaHelper::get_url_schema("order") . $this->id . "'}");
    }

    /**
     * 卖家接单，给买家推送消息
     */
    public function app_accept_push()
    {
        $content = sprintf(Message::PURCHASE_ACCEPT, $this->seller_user->name,$this->server_date);
        $this->save_msg($content, $this->user_id, "{'url':'" . UrlSchemaHelper::get_url_schema("order") . $this->id . "'}");
    }

    /**
     * 买家完成，给卖家推送消息
     */
    public function app_finish_push()
    {
        $this->save_msg(Message::PURCHASE_FINISH, $this->seller_user_id, "{'url':'" . UrlSchemaHelper::get_url_schema("seller_order") . $this->id . "'}");
    }


    public function save_answer_msg($content, $user_id, $params = '{}')
    {
        $message = new Message();
        $message->user_id = $user_id;
        $message->content = $content;
        $message->icon = Message::ICON;
        $message->url_schema = '';
        $message->type = 'anwer';
        $message->type_id = $this->id;
        $message->save();
        //发送推送
        $message->pushMsg($user_id, $content, $params);

    }


    /**
     * 保存消息并推送
     * @param $content
     */
    public function save_question_msg($content, $user_id, $params = '{}')
    {
        $message = new Message();
        $message->user_id = $user_id;
        $message->content = $content;
        $message->icon = Message::ICON;
        $message->url_schema = '';
        $message->type = 'question';
        $message->type_id = $this->id;
        $message->save();
        //发送推送
        $message->pushMsg($user_id, $content, $params);
    }

    /**
     * 保存消息并推送
     * @param $content
     */
    public function save_msg($content, $user_id, $params = '{}')
    {
        $message = new Message();
        $message->user_id = $user_id;
        $message->content = $content;
        $message->icon = Message::ICON;
        $message->url_schema = '';
        $message->type = 'purchase';
        $message->type_id = $this->id;
        $message->save();
        //发送推送
        $message->pushMsg($user_id, $content, $params);
    }

    /**
     * 保存提醒
     */
    public function save_remind()
    {
        if ($this->type == 'Product' && $this->server_date) {
            if (date('Y-m-d H:i:s', strtotime('+1 day')) < date('Y-m-d H:i:00', strtotime($this->server_date))) {
                $remind = new ProductRemind();
                $remind->remind_time = date('Y-m-d H:i:00', strtotime("-1 day", strtotime($this->server_date)));
                $remind->seller_user_id = $this->seller_user_id;
                $remind->user_id = $this->user_id;
                $remind->purchase_id = $this->id;
                $remind->hour = 24;
                $remind->save();
            }
            if (date('Y-m-d H:i:s', strtotime('+2 hour')) < date('Y-m-d H:i:00', strtotime($this->server_date))) {
                $remind = new ProductRemind();
                $remind->remind_time = date('Y-m-d H:i:00', strtotime("-2 hour", strtotime($this->server_date)));
                $remind->seller_user_id = $this->seller_user_id;
                $remind->user_id = $this->user_id;
                $remind->purchase_id = $this->id;
                $remind->hour = 2;
                $remind->save();
            }
        }
    }

    public function _is_buy()
    {
        $p = Purchase::where('product_id', $this->product_id)
            ->where('user_id', $this->user_id)
            ->where('status', '!=', Purchase::STATUS_SELLER_CANCEL)
            ->count();
        if ($p > 0 && !$this->product->allow_repeat) {
            throw new \Exception('您已经下过此订单了，快去订单列表看看吧');
        }
    }

    public function _is_my_product()
    {
        if ($this->type == 'Product' && $this->seller_user_id == $this->user_id) {
            throw new \Exception('您不能对自己进行下单！');
        }
        if ($this->type == 'Dynamic' && $this->seller_user_id == $this->user_id) {
            throw new \Exception('您不能对自己进行打赏！');
        }
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function seller_user()
    {
        return $this->belongsTo(User::class, 'seller_user_id', 'id');
    }

    public function answer_user()
    {
        return $this->belongsTo(User::class, 'to_user_id', 'id');
    }

    public function product()
    {
        return $this->belongsTo(Product::class)->withTrashed();
    }

    public function dynamic()
    {
        return $this->belongsTo(Dynamic::class, 'product_id');
    }


    public function vip()
    {
        return $this->belongsTo(Vip::class, 'product_id');
    }

    public function couponNumber()
    {
        return $this->belongsTo(CouponNumber::class)->withTrashed();
    }

    public function pay_method_desc()
    {
        if ($this->is_payed == static::PAY_WAITING) {
            return '未支付';
        }
        if ($this->pay_method == 'wx') {
            return "微信";
        }
        if ($this->pay_method == 'wx_pub') {
            return "微信公众号";
        }
        if ($this->pay_method == 'wx_mini') {
            return "微信小程序";
        }
        if ($this->pay_method == 'alipay') {
            return "支付宝支付";
        }

        if ($this->pay_method == 'balance') {
            return "余额支付";
        }

        if ($this->pay_method == 'coupon') {
            return "优惠券支付";
        }
    }

    public function payment()
    {
        return $this->hasOne(Payment::class);
    }

    public function refund()
    {
        return $this->hasOne(Refund::class);
    }

    public function question_status_desc()
    {

        switch ($this->status)
        {
            case 6:
                return '审核中';
            case 7:
                return '已超时';
            case 5:
                return '待回答';
            case 8:
                return '查看答案';
        }
    }

    public function question_status_str()
    {

        switch ($this->status) {
            case 1:
                return 'PAY_WAITING';
            case 2:
            case 3:
            case 4:
            case 7:
                return 'OVER_TIME';
            case 9:
            case 10:
                return 'CLOSE';
            case 11:
                return 'REFUND_AUDITING';
            case 12:
                return 'REFUND_PASS';
            case 13:
                return 'REFUND_REJECT';
            case 14:
                return 'REFUND_WITHDRAW';
            case 15:
                return 'REFUND_OVERTIME_PASS';
            case 5:
                return 'WAITING_ANSWER';
            case 6:
                return 'WAIT_AUDITING';
            case 8:
                return 'FINISH';

        }


    }

    public function status_str()
    {
        switch ($this->status) {
            case 1:
                return 'PAY_WAITING';
            case 2:
            case 3:
            case 4:
            case 7:
            case 9:
            case 10:
                return 'CLOSE';
            case 11:
                return 'REFUND_AUDITING';
            case 12:
                return 'REFUND_PASS';
            case 13:
                return 'REFUND_REJECT';
            case 14:
                return 'REFUND_WITHDRAW';
            case 15:
                return 'REFUND_OVERTIME_PASS';
            case 5:
                return 'ACCEPT_WAITING';
            case 6:
                return 'ACCEPT';
            case 8:
                return 'FINISH';
            case 16:
                return 'SELLER_CANCEL_AUDITING';
            case 17:
                return 'SELLER_CANCEL_PASS';
            case 18:
                return 'SELLER_CANCEL_OVERTIME_PASS';
        }
    }
    public function product_total($user_id=0)
    {
        $total = $this->total;
        if ($this->is_payed == static::PAY_WAITING && $this->total == 0) {
            if ($this->product && $this->type == 'Product') {
                $product = $this->product;
                $type = $product->discount_type();
                $p_count = Purchase::serving()->productType()->withTrashed()->where('id', '!=', $this->id)->where('user_id', $this->user_id)->count();
                if ($p_count > 0)
                {
                    $total = $product->price * $this->count;
                    $p_count_topic = Purchase::serving()->productType()->withTrashed()->where('id', '!=', $this->id)->where('user_id',$user_id)->where('product_id',$product->id)->count();
                    if ( $p_count_topic > 0 )
                    {

                        if($type==-1)
                        {
                            $total = $product->price * $this->count;
                        }
                        else if($type==0)
                        {
                            $total = $product->price() * $this->count;
                        }
                        else if($type==1)
                        {
                            $total = $product->price * $this->count;

                        }
                        else if($type==2)
                        {
                            $total = $product->price * $this->count;
                        }
                        else if($type==3)
                        {
                            $total = $product->price * $this->count;
                        }
                        // $total = $product->discount_price($user_id) * $this->count;
                    }
                    else
                    {
                        //判断用户是否购买的活动服务，如果是则判断用户之前是否有已完成订单，如果有则按照原价下单(临时1元购活动使用)--end

                        if($type==-1)
                        {

                            $total = $product->price * $this->count;

                        }
                        else if($type==0)
                        {

                            $total = $product->price() * $this->count;

                        }
                        else if($type==1)
                        {
                            if( $this->count>1 )
                            {
                                $total = ($product->price() * 1) + ($product->price * ($this->count-1));
                            }
                            else
                            {
                                $total = $product->price() * $this->count;
                            }

                        }
                        else if($type==2)
                        {

                            $total = $product->price * $this->count;
                        }
                        else if( $type==3 )
                        {
                            $total = $product->price * $this->count;

                        }


                    }





                }
                else
                {
                    //判断用户是否购买的活动服务，如果是则判断用户之前是否有已完成订单，如果有则按照原价下单(临时1元购活动使用)--end
                    //$total = $product->price() * $this->count;
                    $is_sale = $product->is_sale();              //判断该服务是否在活动中
                    if($is_sale)
                    {
                        if( $this->count>1 )
                        {
                            $total = ($product->price() * 1) + ($product->price * ($this->count-1));
                        }
                        else
                        {
                            $total = $product->price() * $this->count;
                        }

                    }
                    else
                    {

                        $p_count_topic = Purchase::serving()->productType()->withTrashed()->where('id', '!=', $this->id)->where('user_id',$user_id)->where('product_id',$product->id)->count();
                        if( $p_count_topic > 0 )
                        {
                            if($type==-1)
                            {
                                $total = $product->price * $this->count;
                            }
                            else if($type==0)
                            {
                                $total = $product->price() * $this->count;
                            }
                            else if($type==1)
                            {
                                $total = $product->price * $this->count;

                            }
                            else if( $type==2 )
                            {
                                $total = $product->price * $this->count;
                            }
                            else if( $type==3 )
                            {
                                $total = $product->price * $this->count;

                            }

                        }
                        else
                        {

                            if($type==-1)
                            {

                                $total = $product->price * $this->count;

                            }
                            else if($type==0)
                            {

                                $total = $product->price() * $this->count;

                            }
                            else if($type==1)
                            {
                                if( $this->count>1 )
                                {
                                    $total = ($product->price() * 1) + ($product->price * ($this->count-1));
                                }
                                else
                                {
                                    $total = $product->price() * $this->count;
                                }

                            }
                            else if($type==2)
                            {
                                if( $this->count>1 )
                                {
                                    $total = ($product->price() * 1) + ($product->price * ($this->count-1));
                                }
                                else
                                {
                                    $total = $product->price() * $this->count;
                                }
                            }
                            else if($type==3)
                            {
                                $total = $product->price * $this->count;
                            }

                        }

                    }
                }
            }
            if ($this->coupon_number_id)
            {
                //获取使用优惠券后的价格
                $total = $this->couponNumber->coupon_price($total);
            }
        }
        return $total;

    }

    public function total($user_id=0)
    {
        $total = $this->total;
        if ($this->is_payed == static::PAY_WAITING && $this->total == 0) {
            if ($this->product && $this->type == 'Product') {
                $product = $this->product;
                $type = $product->discount_type();
                $p_count = Purchase::serving()->productType()->withTrashed()->where('id', '!=', $this->id)->where('user_id', $this->user_id)->count();
                if ($p_count > 0)
                {
                    $total = $product->price * $this->count;
                    $p_count_topic = Purchase::serving()->productType()->withTrashed()->where('id', '!=', $this->id)->where('user_id',$user_id)->where('product_id',$product->id)->count();
                    if ( $p_count_topic > 0 )
                    {

                        if($type==-1)
                        {
                            $total = $product->price * $this->count;
                        }
                        else if($type==0)
                        {
                            $total = $product->price() * $this->count;
                        }
                        else if($type==1)
                        {
                            $total = $product->price * $this->count;

                        }
                        else if($type==2)
                        {
                            $total = $product->price * $this->count;
                        }
                        else if($type==3)
                        {
                            $total = $product->price * $this->count;
                        }
                        // $total = $product->discount_price($user_id) * $this->count;
                    }
                    else
                    {
                        //判断用户是否购买的活动服务，如果是则判断用户之前是否有已完成订单，如果有则按照原价下单(临时1元购活动使用)--end

                        if($type==-1)
                        {

                            $total = $product->price * $this->count;

                        }
                        else if($type==0)
                        {

                            $total = $product->price() * $this->count;

                        }
                        else if($type==1)
                        {
                            if( $this->count>1 )
                            {
                                $total = ($product->price() * 1) + ($product->price * ($this->count-1));
                            }
                            else
                            {
                                $total = $product->price() * $this->count;
                            }

                        }
                        else if($type==2)
                        {

                            $total = $product->price * $this->count;
                        }
                        else if( $type==3 )
                        {
                            $total = $product->price * $this->count;

                        }


                    }





                }
                else
                {
                    //判断用户是否购买的活动服务，如果是则判断用户之前是否有已完成订单，如果有则按照原价下单(临时1元购活动使用)--end
                    //$total = $product->price() * $this->count;
                    $is_sale = $product->is_sale();              //判断该服务是否在活动中
                    if($is_sale)
                    {
                        if( $this->count>1 )
                        {
                            $total = ($product->price() * 1) + ($product->price * ($this->count-1));
                        }
                        else
                        {
                            $total = $product->price() * $this->count;
                        }

                    }
                    else
                    {

                        $p_count_topic = Purchase::serving()->productType()->withTrashed()->where('id', '!=', $this->id)->where('user_id',$user_id)->where('product_id',$product->id)->count();
                        if( $p_count_topic > 0 )
                        {
                            if($type==-1)
                            {
                                $total = $product->price * $this->count;
                            }
                            else if($type==0)
                            {
                                $total = $product->price() * $this->count;
                            }
                            else if($type==1)
                            {
                                $total = $product->price * $this->count;

                            }
                            else if( $type==2 )
                            {
                                $total = $product->price * $this->count;
                            }
                            else if( $type==3 )
                            {
                                $total = $product->price * $this->count;

                            }

                        }
                        else
                        {

                            if($type==-1)
                            {

                                $total = $product->price * $this->count;

                            }
                            else if($type==0)
                            {

                                $total = $product->price() * $this->count;

                            }
                            else if($type==1)
                            {
                                if( $this->count>1 )
                                {
                                    $total = ($product->price() * 1) + ($product->price * ($this->count-1));
                                }
                                else
                                {
                                    $total = $product->price() * $this->count;
                                }

                            }
                            else if($type==2)
                            {
                                if( $this->count>1 )
                                {
                                    $total = ($product->price() * 1) + ($product->price * ($this->count-1));
                                }
                                else
                                {
                                    $total = $product->price() * $this->count;
                                }
                            }
                            else if($type==3)
                            {
                                $total = $product->price * $this->count;
                            }

                        }

                    }
                }
            }
            if ($this->coupon_number_id)
            {
                //获取使用优惠券后的价格
                $total = $this->couponNumber->coupon_price($total);
            }
        }
        return $total;
    }

    public function timeline($is_seller)
    {
        $arr = array();
        if ($this->status_str() == 'PAY_WAITING')
        {
            $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($this->created_at)), 'title' => '待支付', 'sub_title' => '快去付款邀约卖家吧', 'is_show' => true);
            return $arr;
        }
        if ($this->status_str() == 'CLOSE')
        {
            if ($this->is_payed)
            {
                $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($this->pay_date)), 'title' => '订单已支付', 'sub_title' => ($is_seller || $is_seller == '1') ? '快去接单赚钱吧' : '静静的等待卖家接单吧', 'is_show' => false);
            }
            $cancel_show = true;
            if($this->status==4)
            {
                if($this->return_status == 1 ||$this->return_status == 2  )
                {
                    $cancel_show = false;
                }
            }
            $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($this->close_date)), 'title' => '已取消', 'sub_title' => ($is_seller || $is_seller == '1') ? '由于您拒绝接单或超时未处理' : '卖家拒绝接单或超时未处理', 'is_show' =>$cancel_show);
            if ($this->return_status == 2)
            {
                if($this->status!=7)
                {
                    $refund = $this->refund;
                    $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($refund->updated_at)), 'title' => '已退款', 'sub_title' => ($is_seller || $is_seller == '1') ? '由于您拒绝接单或超时未处理' : '卖家拒绝接单或超时未处理', 'is_show' => true);
                }
            }

            if ($this->return_status == 1)
            {

                if( intval($this->total)==0 && $this->coupon_number_id > 0 )
                {

                }
                else
                {

                  if( $this->status!=7 )
                  {
                      if(!empty($this->refund))
                      {
                          $refund = $this->refund;
                          $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($refund->created_at)), 'title' => '退款中', 'sub_title' => ($is_seller || $is_seller == '1') ? '由于您拒绝接单或超时未处理' : '卖家拒绝接单或超时未处理', 'is_show' => true);
                      }
                  }

                }
            }
            return $arr;
        }
        if ($this->status_str() == 'ACCEPT_WAITING')
        {
            $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($this->pay_date)), 'title' => '订单已支付', 'sub_title' => ($is_seller || $is_seller == '1') ? '快去接单赚钱吧' : '静静的等待卖家接单吧', 'is_show' => true);
            return $arr;
        }
        if ($this->status_str() == 'ACCEPT')
        {
            $starttime = strtotime($this->server_date);
            $endtime = strtotime('+1 hour', strtotime($this->server_date));
            $time = time();

            $is_show = true;
            $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($this->pay_date)), 'title' => '订单已支付', 'sub_title' => ($is_seller || $is_seller == '1') ? '快去接单赚钱吧' : '静静的等待卖家接单吧', 'is_show' => false);
            if( $time>$starttime && $time<$endtime )
            {
                $is_show = false;
            }
            if( $time>=$endtime )
            {
                $is_show = false;
            }
            $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($this->accept_date)), 'title' => ($is_seller || $is_seller == '1') ? '已接单' : '卖家已接单', 'sub_title' => ($is_seller || $is_seller == '1') ? '快去为买家服务吧' : '静静的等待卖家为你服务吧', 'is_show' => $is_show);


            if( $time>$starttime && $time<$endtime )
            {
                $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($this->server_date)), 'title' => ($is_seller || $is_seller == '1') ? '服务中' : '服务中', 'sub_title' => ($is_seller || $is_seller == '1') ? '服务进行中…' : '服务进行中…', 'is_show' => true);
            }

            if( $time>=$endtime )
            {
                $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($this->server_date)), 'title' => ($is_seller || $is_seller == '1') ? '已服务' : '已服务', 'sub_title' => ($is_seller || $is_seller == '1') ? '等待买家确认完成吧' : '尽快确认服务完成吧', 'is_show' => true);
            }

            $arr[] = array('time' => '', 'title' => ($is_seller || $is_seller == '1') ? '等待买家确认' : '等待确认', 'sub_title' => ($is_seller || $is_seller == '1') ? '买家确认完成才可以结束此次服务哦' : '确认完成才可以结束此次服务哦', 'is_show' => false);
            return $arr;
        }
        if ($this->status_str() == 'FINISH')
        {
            $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($this->pay_date)), 'title' => '订单已支付', 'sub_title' => ($is_seller || $is_seller == '1') ? '快去接单赚钱吧' : '静静的等待卖家接单吧', 'is_show' => false);
            $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($this->accept_date)), 'title' => ($is_seller || $is_seller == '1') ? '已接单' : '卖家已接单', 'sub_title' => ($is_seller || $is_seller == '1') ? '快去提供服务吧' : '静静的等待卖家为你服务吧', 'is_show' => false);
            $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($this->close_date)), 'title' => '已完成', 'sub_title' => '买家已确认服务完成哦', 'is_show' => true);
            return $arr;
        }
        if ($this->status_str() == 'REFUND_AUDITING')
        {
            $left_times = 3 - intval($this->times);
            $refund_created_at = empty($this->refund_created_at)?$this->created_at:$this->refund_created_at;
            $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($refund_created_at)), 'title' => ($is_seller || $is_seller == '1')?'请处理退款申请':'等待卖家处理', 'sub_title' => ($is_seller || $is_seller == '1') ? '逾期未响应，系统会自动退款给买家。如果点击同意则会退全款给买家' : '卖家同意或超时未处理将退款给您。如果卖家拒绝，您还有'.$left_times.'次申请机会，建议您与卖家协商一致再申请。', 'is_show' => true);
            return $arr;
        }
        if ($this->status_str() == 'REFUND_PASS'||$this->status_str() == 'REFUND_OVERTIME_PASS' )
        {


            $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($this->close_date)), 'title' => ($is_seller || $is_seller == '1')?'交易关闭':'已退款', 'sub_title' => ($is_seller || $is_seller == '1') ? '退款将全部返还给买家' : '退款将在24小时内原路返回到您的账户', 'is_show' => true);
            return $arr;
        }

        if ( $this->status_str() == 'SELLER_CANCEL_PASS' ||$this->status_str() == 'SELLER_CANCEL_OVERTIME_PASS' )
        {


            $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($this->close_date)), 'title' => ($is_seller || $is_seller == '1')?'交易关闭':'已退款', 'sub_title' => ($is_seller || $is_seller == '1') ? '退款将全部返还给买家' : '退款将在24小时内原路返回', 'is_show' => true);
            return $arr;
        }
        if ($this->status_str() == 'SELLER_CANCEL_AUDITING')
        {
            $left_times = 3 - intval($this->cancel_times);
            $refund_created_at = empty($this->refund_created_at)?$this->created_at:$this->refund_created_at;
            $endtime = strtotime($refund_created_at) + 3600*48;
            $count_time = $this->countTime($endtime);
            $arr[] = array('time' => date('Y-m-d H:i:s', strtotime($refund_created_at)), 'title' => ($is_seller || $is_seller == '1')?'等待买家处理':'请处理退款申请', 'sub_title' => ($is_seller || $is_seller == '1') ? '买家同意或超时未处理会自动退款给买家，如果买家拒绝，您还有'.$left_times.'次申请机会，建议您与买家协商一致再申请' :'同意或超时未处理会自动退款给您', 'is_show' => true);
            return $arr;
        }


        return $arr;
    }

    public function is_serving()
    {

        $is_serving = -1;
        if($this->status == $this::STATUS_SELLER_ACCEPT)
        {

            $starttime = strtotime($this->server_date);
            $endtime = strtotime('+1 hour', strtotime($this->server_date));
            $time = time();
            if( $time>$starttime && $time<$endtime )
            {
                $is_serving = 1;
            }
            if( $time>=$endtime )
            {
                $is_serving = 2;
            }

        }

       return $is_serving;


    }

    public function status_detail()
    {
        switch ($this->status) {
            case 1:
                return '未支付';
            case 2:
            case 3:
            case 4:
            case 7:
            case 9:
            case 10:
                return '订单已关闭';
            case 5:
                return '等待处理';
            case 6:
                return '卖家已同意';
            case 8:
                return '订单完成';
        }
    }


    public function question_status_detail($is_seller = false)
    {
        if ($is_seller)
        {
            switch ($this->status)
            {

                case 5:
                    return '';
                case 7:
                    return '您已超时，赏金已经退回对方账户';
            }
        }
        switch ($this->status)
        {
            case 5:
                return '等待对方回答';
            case 7:
                return '对方超时未回答';
        }


    }
    public function close_detail($is_seller = false)
    {
        if ($is_seller) {
            switch ($this->status) {
                case 2:
                    return '买家已经取消了订单';
                case 3:
                    return '此订单付款时间已过';
                case 4:
                    return '您拒绝了买家的订单';
                case 7:
                    return '您超时未处理订单';
            }
        }
        switch ($this->status) {
            case 2:
                return '您已经取消了订单';
            case 3:
                return '此订单付款时间已过';
            case 4:
                return '卖家拒绝了您的订单';
            case 7:
                return '卖家超时未处理订单';
        }
    }





    /**
     * 保存流水
     */
    public function save_earnings()
    {
        $obj = $this->product;
        $type = 'app';
        if ($this->type == 'Dynamic') {
            $obj = $this->dynamic;
        }
        $detail = '';
        $service_charge = 0;
       // $total = $this->product->price() * $this->count;
        $total = $this->total;
        $user = $obj->user;
        if ($obj->model_name() == 'Product' && $this->source == 'app') {

            $title = $obj->tag_title;
            if(empty($obj->tag_title))
            {
                if($obj->skill)
                {
                    $title = $obj->skill->title;
                }
            }
            $detail = $title;
           // $service_charge = $total * $user->service_charge();
           // $total = $total - $service_charge;
            $service_charge = $this->total * $user->service_charge();
            $total = $this->total - $service_charge;

            if( $this->pay_method=='coupon' && $this->total==0 && $this->coupon_number_id>0 )
            {
                $service_charge = ($this->total +  $this->coupon_total) * $user->service_charge();
                $total = ($this->total+$this->coupon_total) - $service_charge;
            }

            if(  $this->total > 0 && $this->coupon_number_id>0 )
            {
                $service_charge = ($this->total +  $this->coupon_total) * $user->service_charge();
                $total = ($this->total+$this->coupon_total) - $service_charge;

            }



        }

        $from_user = $this->user;
        if ($this->type == 'Dynamic') {
            $detail = $from_user->name . '打赏';
        }



        //增加卖家收益
        $user->add_earnings($total, $this->user_id, $this->id, $this->product_id, $type, EarningsLog::TYPE_IN, ($detail ? $detail : $from_user->name), $service_charge);
        if ($this->type == 'Dynamic') {
            $detail = '打赏' . $user->name;
        }
        //增加买家支出
        $from_user->add_earnings($this->total, $user->id, $this->id, $this->product_id, $type, EarningsLog::TYPE_OUT, ($detail ? $detail : $user->name), $service_charge);
    }


    public function question_finish()
    {

        if ( ($this->status == Purchase::STATUS_SELLER_ACCEPT_WAITING || $this->status == Purchase::STATUS_SELLER_ACCEPT  ) &&  ($this->type == 'Question') )
        {

            $this->status = Purchase::STATUS_FINISH;
            $this->close_date = date('Y-m-d H:i:s');
            $this->sort = 4;
            $this->save();
            $answer_user = $this->answer_user;
            $total = $this->total;
            $type = 'app';
            $service_charge = 0;
            $from_user = $this->user;
            $name = $from_user->name;
            $anonymous = $this->anonymous;
            if( $anonymous == 1)
            {
                $name = '神秘人';
            }
            $detail = '回答'.$name.'的问题';
            $answer_user->add_earnings($total, $this->user_id, $this->id, $this->product_id, $type, EarningsLog::TYPE_IN, ($detail ? $detail :$from_user->name), $service_charge);
            $from_user->add_earnings($total, $this->user_id, $this->id, $this->product_id, $type, EarningsLog::TYPE_OUT, ($detail ? $detail : $from_user->name), $service_charge);


        }



    }
    /**
     * 确认完成方法，将订单设置为已完成状态，并给用户增加收益
     * @return bool
     */
    public function purchase_finish()
    {

        if ($this->status == Purchase::STATUS_SELLER_ACCEPT || $this->type == 'Dynamic') {
            $this->status = Purchase::STATUS_FINISH;
            $this->close_date = date('Y-m-d H:i:s');
            $this->sort = 4;
            $this->save();
            $this->save_earnings();

            if($this->type == 'Product')
            {
                $this->add_contribution_value();
                $this->add_social_status();
                $this->social_status_record();
                $seller = $this->seller_user;
                $seller->change_star_level();
                $this->send_social_status_purchase_msg();

            }

            //完成
            if ($this->source == static::SOURCE_CHUGE) {
                $this->purchase_finish_template();
            }
            if ($this->source == static::SOURCE_APP && $this->type != 'Dynamic') {
                $seller = $this->seller_user;
                $seller->accept_count = $seller->accept_count + 1;
                $seller->save();
                $this->app_finish_push();
            }

            return true;
        }
        return false;
    }

    //新订单模板
    public function purchase_finish_template()
    {
        $url = "http://apiv2test.superxing.cc/chuge";
        $seller_user = $this->seller_user;
        $user = $this->user;
        $product = $this->product;
        $openid = $seller_user->wx_user->open_id;
        \Log::info($openid);
        $ending_time = date('Y-m-d: H:i:s', strtotime($this->created_at) + 900);
        $config = ['openid' => $openid, 'url' => $url];
        $data = array(
            "first" => "您好，您的订单已经完成，可以提现",
            "keyword1" => $product->act,
            "keyword2" => $this->order_no,
            "keyword3" => "订单已完成",
            "keyword4" => $product->server_time,
            "remark" => '点击详情查看',
        );
        WechatTemplateController::change_purchase($config, $data);
    }


    /**
     * 同意订单
     * @return bool
     */
    public function purchase_accept()
    {
        if ($this->status == Purchase::STATUS_SELLER_ACCEPT_WAITING)
        {
            $this->status = Purchase::STATUS_SELLER_ACCEPT;
            $this->accept_date = date('Y-m-d H:i:s');
            $this->sort = 3;
            $this->save();

            if ($this->source == static::SOURCE_APP)
            {
                $this->app_accept_push();
                $this->save_remind();
            }

            if ($this->source == static::SOURCE_CHUGE)
            {
                $this->purchase_accept_template();
                //拒绝其他订单
                $this->reject_purchases();

                $product = Product::where('id', $this->product_id)->first();
                $product->status = 3;
                $product->save();
            }

            return true;
        }
        return false;
    }

    /**
     * 同意退款申请
     * @return bool
     */
    public function purchase_refund_accept()
    {

        if ($this->status == Purchase::STATUS_REFUND_AUDIT)
        {
            $this->status = Purchase::STATUS_REFUND_PASS;
            $this->return_status = Purchase::RETURN_STATUS_WAITING;
            $this->close_date = date('Y-m-d H:i:s');
            $this->sort = 5;
            $this->save();
            $payment = $this->payment;
            $ph = new PingppHelper();
            if( !empty($payment) )
            {
                if( $this->pay_method=='coupon' )
                {


                }
                else if( $this->pay_method=='free' )
                {


                }
                else if( $this->pay_method == 'balance')
                {

                    $this->balance_refund($this,'卖家拒绝订单');


                }
                else
                {
                    $re = json_decode($ph->refundscreate($payment->pay_id, '卖家拒绝订单'), true);
                    $this->save_refund($re);
                }

            }
            $this->refund_coupon();
            if ($this->source == static::SOURCE_CHUGE) {
                //$this->purchase_reject_template();
            }

            if ($this->source == static::SOURCE_APP) {
                //$this->app_reject_push();
            }
            return true;
        }
        return false;

    }

    /**
     * 卖家取消订单 买家同意
     * @return bool
     */
    public function purchase_refund_buyer_accept()
    {

        if ($this->status == Purchase::STATUS_SELLER_CANCEL_AUDIT)
        {
            $this->status = Purchase::STATUS_SELLER_CANCEL_PASS;
            $this->return_status = Purchase::RETURN_STATUS_WAITING;
            $this->close_date = date('Y-m-d H:i:s');
            $this->sort = 5;
            $this->save();
            $payment = $this->payment;
            $ph = new PingppHelper();

            if(!empty($payment))
            {

                if( $this->pay_method=='coupon' )
                {

                }
                else if( $this->pay_method=='free' )
                {

                }
                else if( $this->pay_method == 'balance')
                {

                    $this->balance_refund($this,'卖家取消订单');
                }
                else
                {
                    $re = json_decode($ph->refundscreate($payment->pay_id, '卖家取消订单'), true);
                    $this->save_refund($re);
                }

            }
            $this->refund_coupon();
            if ($this->source == static::SOURCE_CHUGE) {
                //$this->purchase_reject_template();
            }

            if ($this->source == static::SOURCE_APP) {
                //$this->app_reject_push();
            }
            return true;
        }
        return false;

    }

    /**
     * 拒绝退款申请
     * @return bool
     */
    public function purchase_refund_reject()
    {
        if ($this->status == Purchase::STATUS_REFUND_AUDIT)
        {
            $this->status = Purchase::STATUS_SELLER_ACCEPT;
            $this->sort = 3;
            $this->save();
            return true;
        }
        return false;
    }

    /**
     * 卖家取消订单 买家拒绝退款申请
     * @return bool
     */
    public function purchase_refund_buyer_reject()
    {
        if ($this->status == Purchase::STATUS_SELLER_CANCEL_AUDIT)
        {
            $this->status = Purchase::STATUS_SELLER_ACCEPT;
            $this->sort = 3;
            $this->save();
            return true;
        }
        return false;
    }

    //新订单模板
    public function purchase_accept_template()
    {
        $url = "http://apiv2test.superxing.cc/chuge";
        $seller_user = $this->seller_user;
        $user = $this->user;
        $product = $this->product;
        $openid = $user->wx_user->open_id;
        \Log::info($openid);
        $ending_time = date('Y-m-d: H:i:s', strtotime($this->created_at) + 900);
        $config = ['openid' => $openid, 'url' => $url];
        $data = array(
            "first" => "您好，卖家{$seller_user->name}已经接受了您的订单",
            "keyword1" => $product->act,
            "keyword2" => $this->order_no,
            "keyword3" => "卖家已同意",
            "keyword4" => $product->server_time,
            "remark" => '点击详情查看',
        );
        WechatTemplateController::change_purchase($config, $data);
    }


    public function reject_purchases()
    {
        //其他订单拒绝订单
        if ($purchases = Purchase::where('product_id', $this->product_id)->where('id', '!=', $this->id)->get()) {
            foreach ($purchases as $purchase) {

                if (Refund::where('purchase_id', $purchase->id)->count() > 0) {
                    \Log::info("[Purchase_id: {$purchase->id}] 已经退款");
                    continue;
                }
                if ($purchase->payment) {
                    $purchase->status = Purchase::STATUS_SELLER_CANCEL;
                    $purchase->return_status = Purchase::RETURN_STATUS_WAITING;
                    $purchase->sort = 5;
                    $purchase->close_date = date('Y-m-d H:i:s');
                    $purchase->save();
                    $payment = $purchase->payment;
                    $ph = new PingppHelper();

                    if(!empty($payment))
                    {

                        if( $purchase->pay_method=='coupon' )
                        {

                        }
                        else if( $purchase->pay_method=='free' )
                        {

                        }
                        else if( $purchase->pay_method == 'balance')
                        {

                            $this->balance_refund($purchase,'卖家拒绝订单');
                        }
                        else
                        {
                            $re = json_decode($ph->refundscreate($payment->pay_id, '卖家拒绝订单'), true);
                            $this->save_refund($re);
                        }

                    }








                } else {
                    $purchase->status = Purchase::STATUS_SELLER_CANCEL;
                    $purchase->close_date = date('Y-m-d H:i:s');
                    $purchase->save();
                }

                $this->purchase_reject_template_other($purchase);
            }
        }

    }

    /**
     * 拒绝订单，并给用户退款
     * @return bool
     */
    public function purchase_reject()
    {
        if ($this->status == Purchase::STATUS_SELLER_ACCEPT_WAITING) {
            $this->status = Purchase::STATUS_SELLER_CANCEL;
            $this->return_status = Purchase::RETURN_STATUS_WAITING;
            $this->close_date = date('Y-m-d H:i:s');
            $this->sort = 5;
            $this->save();
            $payment = $this->payment;
            $ph = new PingppHelper();
            if(!empty($payment))
            {

                if( $this->pay_method=='coupon' )
                {

                }
                else if( $this->pay_method=='free' )
                {

                }
                else if( $this->pay_method == 'balance')
                {

                    $this->balance_refund($this,'卖家拒绝订单');
                }
                else
                {
                    $re = json_decode($ph->refundscreate($payment->pay_id, '卖家拒绝订单'), true);
                    $this->save_refund($re);
                }

            }
            $this->refund_coupon();

            if ($this->source == static::SOURCE_CHUGE) {
                $this->purchase_reject_template();
            }
            if ($this->source == static::SOURCE_APP) {
                $this->app_reject_push();
            }
            return true;
        }
        return false;
    }

    /**
     * 后台强制取消订单，并给用户退款
     * @return bool
     */
    public function purchase_admin_cancel($name, $note)
    {
        if (!in_array($this->status_str(), ['CLOSE', 'FINISH'])) {
            $this->status = Purchase::STATUS_ADMIN_CANCEL;
            if ($this->status_str() != 'PAY_WAITING') {
                $this->return_status = Purchase::RETURN_STATUS_WAITING;
            }
            $this->close_date = date('Y-m-d H:i:s');
            $this->sort = 5;
            $this->cancel_name = $name;
            $this->cancel_note = $note;
            $this->save();
            $this->refund_coupon();


            if ($this->status_str() != 'PAY_WAITING') {
                $payment = $this->payment;
                $ph = new PingppHelper();
                if(!empty($payment))
                {

                    if( $this->pay_method=='coupon' )
                    {

                    }
                    else if( $this->pay_method=='free' )
                    {

                    }
                    else if( $this->pay_method == 'balance')
                    {

                        $this->balance_refund($this,'后台强制取消订单');
                    }
                    else
                    {
                        $re = json_decode($ph->refundscreate($payment->pay_id, '后台强制取消订单'), true);
                        $this->save_refund($re);
                    }

                }



            }
            if ($this->source == static::SOURCE_APP) {
                $this->app_admin_cancel_push();
            }
            return true;
        }
        return false;
    }

    public function purchase_reject_template_other($purchase)
    {
        $url = "http://apiv2test.superxing.cc/chuge";
        $seller_user = $purchase->seller_user;
        $user = $purchase->user;
        $product = $purchase->product;
        $openid = $user->wx_user->open_id;
        \Log::info($openid);
        $ending_time = date('Y-m-d: H:i:s', strtotime($purchase->created_at) + 900);
        $config = ['openid' => $openid, 'url' => $url];
        $data = array(
            "first" => "您好，卖家{$seller_user->name}拒绝了您的订单",
            "keyword1" => $product->act,
            "keyword2" => $purchase->order_no,
            "keyword3" => "卖家已拒绝",
            "keyword4" => $product->server_time,
            "remark" => '点击详情查看',
        );
        WechatTemplateController::change_purchase($config, $data);
    }

    //拒绝订单
    public function purchase_reject_template()
    {
        $url = "http://apiv2test.superxing.cc/chuge";
        $seller_user = $this->seller_user;
        $user = $this->user;
        $product = $this->product;
        $openid = $user->wx_user->open_id;
        \Log::info($openid);
        $ending_time = date('Y-m-d: H:i:s', strtotime($this->created_at) + 900);
        $config = ['openid' => $openid, 'url' => $url];
        $data = array(
            "first" => "您好，卖家{$seller_user->name}拒绝了您的订单",
            "keyword1" => $product->act,
            "keyword2" => $this->order_no,
            "keyword3" => "卖家已拒绝",
            "keyword4" => $product->server_time,
            "remark" => '点击详情查看',
        );
        WechatTemplateController::change_purchase($config, $data);
    }


    /**
     * 订单支付后给卖家发送短信
     */
    public function question_payed_sms()
    {
        $user = $this->answer_user;
        if ($user && $user->phone())
        {

            $name =  $this->user->name;
            $anonymous = $this->anonymous;
            if( $anonymous == 1)
            {
                $name = '神秘人';
            }
            $yunXinServerAPI = new YunXinServerAPI();
            $yunXinServerAPI->questionPayedSmsTemplate($user->phone(), $name);
        }
    }

    /**
     * 订单支付后给卖家发送短信
     */
    public function payed_sms()
    {
        $user = $this->seller_user;

        if ($user && $user->phone() && $this->product && ($this->product->skill ||$this->product->tag_title)) {
            $yunXinServerAPI = new YunXinServerAPI();
            $title = $this->product->tag_title;
            if(empty($this->product->tag_title))
            {
                if($this->product->skill)
                {
                    $title = $this->product->skill->title;
                }
            }
            $yunXinServerAPI->payedSmsTemplate($user->phone(), $title, $this->order_no);
        }
    }


    public function save_refund($re)
    {
        $refund = Refund::where('purchase_id', $this->id)->first();
        if (!$refund) {
            $refund = new Refund();
        }
        $refund->refund_id = $re['id'];
        $refund->purchase_id = $this->id;
        $refund->object = $re['object'];
        $refund->order_no = $re['order_no'];
        $refund->amount = $re['amount'];
        $refund->created = $re['created'];
        $refund->succeed = $re['succeed'];
        $refund->status = $re['status'];
        $refund->time_succeed = $re['time_succeed'];
        $refund->description = $re['description'];
        $refund->failure_code = $re['failure_code'];
        $refund->failure_msg = $re['failure_msg'];
        $refund->charge = $re['charge'];
        $refund->charge_order_no = $re['charge_order_no'];
        $refund->transaction_no = $re['transaction_no'];

        $refund->save();
    }

    public function save_vip()
    {
        $vip = $this->vip;
        if ($vip) {
            $vip_user = new VipUser();
            $vip_user->user_id = $this->user_id;
            $vip_user->vip_id = $vip->id;
            $vip_user->start_date = date('Y-m-d');
            $vu = VipUser::where('user_id', $this->user_id)->where('start_date', '<=', date('Y-m-d'))->where('end_date', '>=', date('Y-m-d'))->orderBy('end_date', 'desc')->first();
            if ($vu) {
                $vip_user->end_date = date('Y-m-d', strtotime('+' . $vip->day_num . ' month', strtotime($vu->end_date)));
            } else {
                $vip_user->end_date = date('Y-m-d', strtotime('+' . $vip->day_num . ' month'));
            }
            $vip_user->save();
        }
    }

    public function countTime($endtime)
    {

        $time =  $endtime - time();
        $date_str = '';
        $d = floor($time/60/60/24);
        $h = floor($time/60/60%24);
        $m = floor($time/60%60);
        if( $d>0 )
        {
            $date_str .=$d.'天';
        }
        if($h >0 )
        {
            $date_str .=$d.'小时';
        }

        if( $m>0 )
        {
            $date_str .=$m.'分';
        }

        return $date_str;
    }
    /**
     * 判断当前订单状态是否为可聊天状态
     * @return bool
     */
    public function is_chat()
    {
        //return true;
        if (in_array($this->status_str(), ['ACCEPT_WAITING', 'ACCEPT'])) {
            return true;
        }
        //\Log::info($this,['==================usthis==========================']);
        $user = $this->user;

        if ($user->identity == User::IDENTITY_SELLER) {
            return true;
        }
        if ($user->vip_day_count() > 0) {
            return true;
        }
        return false;
    }


    public function balance_refund($purchase,$description='卖家拒绝订单')
    {
        $re = array();
        $re['id'] = 'balance_'.$purchase->id;
        $re['object'] = 'refund';
        $re['order_no'] = $purchase->order_no;
        $re['amount'] = $purchase->total*100;
        $re['created'] = time();
        $re['succeed'] = 1;;
        $re['status'] = 'succeeded';
        $re['time_succeed'] = '';
        $re['description'] = $description;
        $re['failure_code'] = 0;
        $re['failure_msg'] = '';
        $re['charge'] = 'balance_'.$purchase->id;
        $re['charge_order_no'] = $purchase->order_no;
        $re['transaction_no'] = $purchase->order_no;
        $re['type'] = 1;
        $purchase->save_refund($re);
        $user = $purchase->user;
        $product = $purchase->product;
        $title = $product->tag_title;
        if(empty($product->tag_title))
        {
            if($product->skill)
            {
                $title = $product->skill->title;
            }
        }
        $detail = $title;
        $user->earnings = $user->earnings + $purchase->total;
        $user->save();
        $user->add_earnings($purchase->total, $user->id, $purchase->id, $purchase->product->id, Purchase::SOURCE_APP,4, ($detail ? $detail : $user->name));

    }


    public function send_social_status_purchase_msg()
    {

        $seller = $this->seller_user;
        $unit = 10;
        $value = 0;
        $product_total = $this->product_total;
        if($product_total>=1)
        {
            $value = $this->product_total * $unit;
        }
        $url = null;
        $content =  $content = sprintf(Message::SOCIA_STATUS_PURCHASE,$value);
        $message = new Message();
        $message->user_id = $seller->id;
        $message->content = $content;
        $message->icon = Message::SOCIA_STATUS_UP_ICON;
        $message->url_schema = $url;
        $message->type_id = $this->id;
        $message->type = 'socialstatus';
        $message->save();
       // $message->pushMsg($seller->id, $content);
    }

    public function add_social_status()
    {
        $seller = $this->seller_user;
        $product_total = $this->product_total;
        $unit = 10;
        if($product_total>=1)
        {
            $social_status = $this->product_total * $unit;
            $seller->social_status = $seller->social_status + $social_status;
            $seller->show_social_status = $seller->social_status + intval($seller->operation_social_status);
            $seller->save();

        }

    }

    public function social_status_record()
    {

        $user = $this->user;
        $seller = $this->seller_user;
        $fan = $seller->myFanUsers()->where('user_id', $user->id)->first();
        if($fan)
        {

            $unit = 10;
            $product_total = $this->product_total;
            $value = $this->product_total * $unit;
            if($product_total>=1)
            {
                $detail = "$user->name 购买偶像 $seller->name 服务 $seller->name 身价增加 $value ";
                $social_status_log =  new SocialStatusLog();
                $social_status_log->type = SocialStatusLog::STATUS_PURCHASE_FINISH;
                $social_status_log->detail = $detail;
                $social_status_log->source = 'app';
                $social_status_log->value = $value;
                $social_status_log->user_id = $seller->id;

                $social_status_log->product_id= $this->product->id;
                $social_status_log->purchase_id= $this->id;

                $social_status_log->save();
            }


        }




    }
    /**
     * 增加贡献值
     */
    public function add_contribution_value()
    {
        $user = $this->user;
        $seller = $this->seller_user;
        $fan = $seller->myFanUsers()->where('user_id', $user->id)->first();
        if( $fan )
        {

           $contribution_value_log = new ContributionValueLog();
           $contribution_value_log->user_id  = $user->id;
           $contribution_value_log->to_user_id  = $seller->id;
           $product_total = $this->product_total;
           $unit = 1000;
           if($product_total>=1)
           {
               $value = $this->product_total * $unit;
               $detail =  $user->name." "."购买"."偶像"." ".$seller->name." "."服务"." "."金额".$this->product_total." "."贡献值".$value;
               $contribution_value_log->value  = $value;
               $contribution_value_log->detail  = $detail;
               $contribution_value_log->type  = ContributionValueLog::TYPE_SERVICE;
               $contribution_value_log->source = $this->source;
               $contribution_value_log->product_id= $this->product->id;
               $contribution_value_log->purchase_id= $this->id;
               $contribution_value_log->save();

               $fan->value = $fan->value + $value;
               $fan->user_value = $fan->user_value + $value;
               $fan->save();

               $fan->rank = $fan->user_rank();
               $fan->save();


           }
        }

    }
}
